﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using LibrarySystem.Models;
using LibrarySystem.LibraryUtils.DAL.DAOs;
using PagedList;
using System.Web.Security;
namespace LibrarySystem.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index(int page = 1)
        {
            Library_Books libBook = new Library_Books();
            int pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"]);
            List<BookModel> list = libBook.GetDataList();
            //
            Library_Categories libCat = new Library_Categories();
            ViewBag.ParitalCategories = libCat.GetDataList();
            //
            List<BookModel> mostBorrowed = libBook.GetDataList(null, null, null, 0, 0,
                int.Parse(ConfigurationManager.AppSettings["ShowTimes"]), "BorrowTimes DESC");
            ViewBag.MostBorrowed = mostBorrowed;
            return View(list.ToPagedList(page, pageSize));
        }

        public ActionResult TimKiem(int page = 1, string bookCode = null, string bookName = null, string bookAuthor = null, int category = 0)
        {
            Library_Books libBook = new Library_Books();
            int pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"]);
            List<BookModel> list = libBook.GetDataList(bookCode, bookName, bookAuthor, category);
            //
            //
            List<BookModel> mostBorrowed = libBook.GetDataList(null, null, null, 0, 0,
                 int.Parse(ConfigurationManager.AppSettings["ShowTimes"]), "BorrowTimes DESC");
            ViewBag.MostBorrowed = mostBorrowed;
            
            Library_Categories libCat = new Library_Categories();
            var cateFilter = libCat.GetCateComboxList().Select(c => new SelectListItem { Text = c.CategoryName, Value = c.ID.ToString() }).ToList();
            cateFilter.Insert(0, new SelectListItem { Selected = true, Value = "0", Text = "---Xin chọn thể loại---" });
            ViewBag.Categories = cateFilter;
            ViewBag.ParitalCategories = libCat.GetDataList();
            return View(list.ToPagedList(page, pageSize));
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult SachKhongTonTai()
        {
            return View();
        }

        public ActionResult ThongTinSach(string id = null)
        {
            Library_Books libBook = new Library_Books();
            if (string.IsNullOrEmpty(id))
                return RedirectToAction("TimKiem");
            List<BookDetailModel> list = libBook.GetBookDetail(id);
            if (list != null || list.Count > 0)
                return View(list.Single<BookDetailModel>());
            else
                return RedirectToAction("SachKhongTonTai");
        }
    }
}
